
using Admin2505.Application.Dto;
using Admin2505.Application.Services;
using Admin2505.Domain.Common;
using Admin2505.Domain.Entityes.App;
using Admin2505.Domain.Reposoitories;
using Microsoft.AspNetCore.Mvc;


namespace Admin2505.Api.Controllers;

[ApiController]
[Route("api/[controller]")]

public class UserController: ControllerBase
{
    private readonly UserService _userService;
    private readonly IRepository<AppRole> _roleService;

    public UserController(UserService userService,IRepository<AppRole> roleService)
    {
        _userService = userService;
        _roleService=roleService;

    }

    [HttpPost]
    public async Task<IActionResult> Create([FromBody] CreateUserDto dto)
    {
        var user = await _userService.CreateUserAsync(dto.UserName,dto.Password);
        return Ok(new {user.Id,user.Username});

    }

    [HttpPut("{id}/password")]

    public async Task<IActionResult> ChangePassword (Guid id,[FromBody] ChangePasswordDto dto)
    {
        await _userService.ChangePasswordAsync(id,dto.NewPassword);
        return Ok();
    }
    [HttpPut("{userId}/assign-role")]
    public async Task<IActionResult> AssignRole(Guid userId, [FromBody] AssignRoleDto dto)
    {
        // var role = new AppRole(dto.RoleName); // 这里只做演示，实际应通过仓储获取角色
        // await _userService.AssignRoleAsync(id, role);
        // 正确：应通过仓储查找
        
        var role = await _roleService.GetByIdAsync(dto.roleId) ?? throw new Exception("角色不存在00");
        await _userService.AssignRoleAsync(userId, role);
        return Ok();
    }

    [HttpPut("{id}/remove-role")]
    public async Task<IActionResult> RemoveRole (Guid id,[FromBody] AssignRoleDto dto)
    {
        var role= await _roleService.GetByIdAsync(dto.roleId) ?? throw new Exception("角色不存在00");
        await _userService.RemoveRoleAsync(id,role);
        return Ok();

    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetById (Guid id)
    {
        var user = await _userService.GetUserByAsync(id);
        if(user==null) return NotFound();
        return Ok(new UserDto(user.Id,user.Username));

    }
    [HttpGet]
    public async Task<IActionResult> GetAll([FromQuery]PagedrequestDto pagedrequest)
    {
        var users= await _userService.GetPageUserAsync(pagedrequest.PageIndex,pagedrequest.PageSize);

        var dto = new PageResultDto<UserDto>
        {
            Items = users.Items.Select(x=>new UserDto (x.Id,x.Username)),
            Totalcoun= users.Totalcoun
        };

  
        return Ok(dto);
    }


    // public record CreateUserDto(string UserName,string Password);
    // public record ChangePasswordDto(string NewPassword);

    // public record AssignRoleDto(string RoleName);

    // public record UserDto (Guid Id,string UserName);

}